//
//  IGiGameViewController.m
//  iGameApp
//
//  Created by lanou on 16/1/9.
//  Copyright © 2016年 WYC. All rights reserved.
//

#import "IGiGameViewController.h"
#import "IGHistoryList.h"
#import "IGFindRadioPlayViewController.h"
@interface IGiGameViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate>

@end

@implementation IGiGameViewController

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"OPEN" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"CLOSE" object:nil];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    _tableView.frame = CGRectMake(0, 64, kScreenWidth, kScreenHeight - 113);
    CGRect frame = _headerView.frame;
    frame.size.height = 180 + 30 + (kScreenWidth - 20) / 3 * 1.5 * 2 + 40;
    _headerView.frame = frame;
    [_tableView setTableHeaderView:_headerView];
   
}
- (void)viewWillAppear:(BOOL)animated {
    IGRightTabBarController *tabBarController = (IGRightTabBarController *)self.navigationController.parentViewController;
    tabBarController.tabBar.hidden = NO;
    IGCustomNavigationController *navC = (IGCustomNavigationController *)self.navigationController;
    navC.iconButton.hidden = NO;
    navC.backButton.hidden = YES;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    _requestStart = 0;
    [self setScrollView];
    [self setCollection];
    [self setTableViews];
    [self setUpRoundData];
    [self setPageControll];
    [self setUpCollectionData];
    [self setUpTableViewData];
     [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(timerChange:) userInfo:@"s" repeats:YES];
    // Do any additional setup after loading the view from its nib.
    [self MJRefreshing];
    
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(notification:) name:@"OPEN" object:nil];
    [center addObserver:self selector:@selector(notification1:) name:@"CLOSE" object:nil];
    
}

//  实现接到通知的方法
//  通知是通知中心发的 接到的是一个通知 而不是通知中心
- (void)notification:(NSNotification *)notification {
    _headerView.firstBtn.userInteractionEnabled = YES;
    _headerView.secondBtn.userInteractionEnabled = YES;
    _headerView.thirdBtn.userInteractionEnabled = YES;
}

- (void)notification1:(NSNotification *)notification {
    _headerView.firstBtn.userInteractionEnabled = NO;
    _headerView.secondBtn.userInteractionEnabled = NO;
    _headerView.thirdBtn.userInteractionEnabled = NO;
}

// 计时器
- (void)timerChange:(NSTimer *)timer {
    CGFloat x = _headerView.scrollView.contentOffset.x / kScreenWidth;
    if (x == 2) {
        [_headerView.scrollView setContentOffset:CGPointMake(0, 0) animated:NO];
        [_headerView.scrollView setContentOffset:CGPointMake(kScreenWidth, 0) animated:YES];
    } else {
        [_headerView.scrollView setContentOffset:CGPointMake(kScreenWidth * (x + 1), 0) animated:YES];
    }
}

#pragma mark -- 数据请求
//  轮播图数据请求
- (void)setUpRoundData {
    _roundDataArray = [NSMutableArray array];
    [IGAFNetworking requestWithUrlString:@"http://www.imbatv.cn/api_2_4_0/getImbaTopicSlideShow" parDic:nil metho:GET finish:^(NSDictionary *dataDic) {
        NSArray *array = dataDic[@"data"];
        for (NSDictionary *dic in array) {
            IG_iGameRoundModel *model = [[IG_iGameRoundModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [_roundDataArray addObject:model];
        }
        IG_iGameRoundModel *model1 = _roundDataArray[0];
        IG_iGameRoundModel *model2 = _roundDataArray[1];
        IG_iGameRoundModel *model3 = _roundDataArray[0];
        [_headerView.firstBtn sd_setImageWithURL:[NSURL URLWithString:model1.img] forState:(UIControlStateNormal)];
        [_headerView.secondBtn sd_setImageWithURL:[NSURL URLWithString:model2.img] forState:(UIControlStateNormal)];
        [_headerView.thirdBtn sd_setImageWithURL:[NSURL URLWithString:model3.img] forState:(UIControlStateNormal)];
        [_headerView.collectionView reloadData];
    } error:^(NSError *requestError) {
        NSLog(@"请求失败");
    }];
}

//  collection数据请求
- (void)setUpCollectionData {
    _collectionDataArray = [NSMutableArray array];
    [IGAFNetworking requestWithUrlString:@"http://www.imbatv.cn/api_2_4_0/getImbaHotAlbums" parDic:nil metho:GET finish:^(NSDictionary *dataDic) {
        NSArray *array = dataDic[@"data"];
        for (NSDictionary *dic in array) {
            IG_iGameCollectionModel *model = [[IG_iGameCollectionModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [_collectionDataArray addObject:model];
        }
        [_headerView.collectionView reloadData];
    } error:^(NSError *requestError) {
        NSLog(@"请求失败");
    }];
}

//  tableview数据请求
- (void)setUpTableViewData {
  
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    parDic[@"start"] = [NSString stringWithFormat:@"%ld",_requestStart];
    [IGAFNetworking requestWithUrlString:@"http://www.imbatv.cn/api_2_4_0/getImbaVideos?num=10" parDic:parDic metho:GET finish:^(NSDictionary *dataDic) {
        if (_requestStart == 0) {
    
            [_tableViewDataArray removeAllObjects];
        }
        NSNumber *code = dataDic[@"code"];
        if ([code integerValue] == 400) {
            [_tableView reloadData];
            [_tableView.mj_footer endRefreshingWithNoMoreData];

        } else {
        _tableViewDataArray = [NSMutableArray array];
        NSArray *array = dataDic[@"data"];
            if (array.count != 0) {
                for (NSDictionary *dic in array) {
                    IG_iGameTableViewModel *model = [[IG_iGameTableViewModel alloc] init];
                    [model setValuesForKeysWithDictionary:dic];
                    [_tableViewDataArray addObject:model];
                }
                [_tableView reloadData];
                [_tableView.mj_footer endRefreshing];
                [_tableView.mj_header endRefreshing];
            }
    }
    }
      error:^(NSError *requestError) {
        NSLog(@"请求失败");
    }];
    
}

//  上下拉刷新
- (void)MJRefreshing {
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _requestStart = 0;
        [self setUpTableViewData];
    }];
    _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _requestStart += 10;
        [self setUpTableViewData];
    }];
}
#pragma mark -- 控件设置
//  设置scrollview
- (void)setScrollView {
    _headerView = [[UINib nibWithNibName:@"IG_headerView" bundle:nil] instantiateWithOwner:self options:nil].firstObject;
    [_tableView setTableHeaderView:_headerView];
  

    _headerView.scrollView.frame = CGRectMake(0, 0, kScreenWidth, 180);
    _headerView.scrollView.contentSize = CGSizeMake(kScreenWidth * 3, 180);
    [_headerView.scrollView setContentOffset:CGPointMake(kScreenWidth, 0)];
    _headerView.scrollView.delegate = self;
}

//  设置tableView
- (void)setTableViews {
    _tableView.rowHeight = 100;
    [_tableView registerNib:[UINib nibWithNibName:@"IG_iGameTableViewCell" bundle:nil] forCellReuseIdentifier:@"MyTableViewCell"];
}

//  设置collectionView
- (void)setCollection {
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    [flowLayout setItemSize:CGSizeMake((kScreenWidth - 20) / 3, (kScreenWidth - 20) / 3 * 1.5)];
    
    
    
    flowLayout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5);
    flowLayout.minimumInteritemSpacing = 5;
    flowLayout.minimumLineSpacing = 5;
    [_headerView.collectionView setCollectionViewLayout:flowLayout];
    _headerView.collectionView.layer.masksToBounds = YES;
    _headerView.collectionView.delegate = self;
    _headerView.collectionView.dataSource = self;
    [_headerView.collectionView registerNib:[UINib nibWithNibName:@"IG_iGameCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"MyCollectionCell"];
    [_headerView.firstBtn addTarget:self action:@selector(firstBtnClick:) forControlEvents:(UIControlEventTouchUpInside)];
    [_headerView.secondBtn addTarget:self action:@selector(secondBtnClick:) forControlEvents:(UIControlEventTouchUpInside)];
    [_headerView.thirdBtn addTarget:self action:@selector(firstBtnClick:) forControlEvents:(UIControlEventTouchUpInside)];
   
}

//  轮播图点击方法
- (void)firstBtnClick:(UIButton *)sender {
    IG_iGameRoundModel *model = _roundDataArray[0];
    IGFindRadioPlayViewController *roundVC = [[IGFindRadioPlayViewController alloc] init];
    roundVC.isFindPushHere = YES;
    roundVC.vid = model.vidStr;
    [self.navigationController pushViewController:roundVC animated:YES];
}

- (void)secondBtnClick:(UIButton *)sender {
    IG_iGameRoundModel *model = _roundDataArray[1];
    IGFindRadioPlayViewController *roundVC = [[IGFindRadioPlayViewController alloc] init];
    roundVC.vid = model.vidStr;
    roundVC.isFindPushHere = YES;
    [self.navigationController pushViewController:roundVC animated:YES];
}

//  设置pageControl
- (void)setPageControll {
    [_headerView.pageControl addTarget:self action:@selector(pageChange:) forControlEvents:(UIControlEventValueChanged)];
}


- (void)pageChange:(UIPageControl *)pageControl {
    [_headerView.scrollView setContentOffset:CGPointMake((pageControl.currentPage + 1) * kScreenWidth, 0)];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    _headerView.pageControl.currentPage = scrollView.contentOffset.x / kScreenWidth - 1;
    if (_headerView.scrollView.contentOffset.x == kScreenWidth * 2) {
        [_headerView.scrollView setContentOffset:CGPointMake(0, 0)];
    } if (_headerView.scrollView.contentOffset.x == 0) {
        [_headerView.scrollView setContentOffset:CGPointMake(kScreenWidth * 2, 0)];
        _headerView.pageControl.currentPage = 1;
    }
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (_headerView.scrollView.contentOffset.x > kScreenWidth * 2) {
        [_headerView.scrollView setContentOffset:CGPointMake(0, 0)];
    }
    if (_headerView.scrollView.contentOffset.x < 0) {
        [_headerView.scrollView setContentOffset:CGPointMake(kScreenWidth * 2, 0)];
    }
    
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    if (_headerView.pageControl.currentPage == 1) {
        _headerView.pageControl.currentPage = 0;
    } else {
        _headerView.pageControl.currentPage += 1;
    }
}

#pragma mark --  collectionView协议方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 6;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    IG_iGameCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MyCollectionCell" forIndexPath:indexPath];
    if (_collectionDataArray.count != 0) {
     
    if (indexPath.row != 5) {
        cell.model = _collectionDataArray[indexPath.row];
    } else {
        cell.photoView.image = [UIImage imageNamed:@"bg"];
        cell.nameLabel.text = @"iGame";
        [cell.nameLabel adjustsFontSizeToFitWidth];
    }
}
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row != 5) {
        IG_CollectionViewDetailController *collectionDetailVC = [[IG_CollectionViewDetailController alloc] init];
        if (_collectionDataArray.count != 0) {
            IG_iGameCollectionModel *model = _collectionDataArray[indexPath.row];
            collectionDetailVC.album_id = model.album_idStr;
        }
        [self.navigationController pushViewController:collectionDetailVC animated:YES];
    } else {
        IG_iGameMoreViewController *moreVC = [[IG_iGameMoreViewController alloc] init];
        moreVC.index = -1;
        [self.navigationController pushViewController:moreVC animated:YES];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -- scrollview协议方法

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _tableViewDataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    IG_iGameTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyTableViewCell" forIndexPath:indexPath];
    cell.model = _tableViewDataArray[indexPath.section];
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    IGFindRadioPlayViewController *detailVC = [[IGFindRadioPlayViewController alloc] init];
    detailVC.isFindPushHere = YES;
    IG_iGameTableViewModel *model = _tableViewDataArray[indexPath.row];
    [[IGHistoryList defaultIGHistoryList] saveDataAtLoacllyWithTitle:model.title img:model.image vid:model.vidStr];
    detailVC.vid = model.vidStr;
    [self.navigationController pushViewController:detailVC animated:YES];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
